package hust.cs.javacourse.search.index.impl;

import hust.cs.javacourse.search.index.AbstractDocument;
import hust.cs.javacourse.search.index.AbstractIndex;
import hust.cs.javacourse.search.index.AbstractIndexBuilder;

import hust.cs.javacourse.search.index.AbstractDocumentBuilder;

import java.io.File;

public class IndexBuilder extends AbstractIndexBuilder {

   public IndexBuilder (AbstractDocumentBuilder docBuilder) {
       super(docBuilder);
   }

    @Override
    public AbstractIndex buildIndex(String rootDirectory) {
        File file = new File(rootDirectory);                //读取目录下所有文件
        File[] fileList = file.listFiles();
        AbstractDocument document;                          //声明Document引用
        AbstractIndex index = new Index();                  //声明Index引用

        //每读取一个文件，创建一个Document对象，并加入到Index中
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isFile()) {                     //判断是否是文件
                String fileName = fileList[i].getName();    //获取文件名
                String docPath = rootDirectory + fileName;
                //System.out.println("okokokokok");
                document = this.docBuilder.build(this.docId, docPath, fileList[i]); //创建document对象
                index.addDocument(document);                //将Document对象添加到Index中
                this.docId++;                               //文档ID加一
            }
        }
        return index;
    }
}
